import Axios from "axios";
import router from '@/router'
import { Notify } from "vant";
import { getToken, removeToken  } from "./token"   //setToken
// import { getNewTokenAPI } from './api'

const axios = Axios.create({
    baseURL: 'http://geek.itheima.net/',
    timeout: 20000
})

//请求拦截器
axios.interceptors.request.use((config) => {

    if (getToken()?.length > 0 && config.headers.Authorization === undefined) {
        config.headers.Authorization = `Bearer ${getToken()}`
    }

    return config
}, (error) => {
    return Promise.reject(error)
})

//响应拦截器
axios.interceptors.response.use((response) => {
    return response
}, async (error) => {

    if (error.response.status === 401) {
        Notify({ type: 'warning', message: '身份已过期' })
        removeToken()
        router.replace(`/login?path=${router.currentRoute.fullPath}`)

        /* const res = await getNewTokenAPI()
        //更新token在本地
        setToken(res.data.data.token)
        //更新新的token在请求头里
        error.config.headers.Authorization = `Bearer ${res.data.data.token}`
        //未完成的这次请求，在发一次
        return axios(error.config) */
        // console.log(res);
    } /* else if (error.response.status === 500 && error.config.url === '/v1_0/authorizations' && error.config.method === 'put') {
        localStorage.clear()
        Notify({ type: 'warning', message: '身份已过期' })

        router.replace('/login')
    } */

    return Promise.reject(error)
})

export default ({ url, method = 'GET', params = {}, data = {}, headers = {} }) => {
    return axios({
        url,
        method,
        params,
        data,
        headers,
    })
}